import {
  CoolController,
  BaseController,
  CoolTag,
  TagTypes,
} from '@cool-midway/core';
import { Body, Get, Inject, Post, Query } from '@midwayjs/core';
import { PayOrderEntity } from '../../entity/order';
import { PayOrderService } from '../../service/order';
import { PluginService } from '../../../plugin/service/info';
import { UserWxService } from '../../../user/service/wx';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { PayBalanceService } from '../../service/balance';
import { UserInfoEntity } from '../../../user/entity/info';

/**
 * 支付模块-用户端订单控制器
 */
@CoolController({
  api: [],
  entity: PayOrderEntity,
})
export class AppPayOrderController extends BaseController {
  @Inject()
  ctx;

  @Inject()
  payOrderService: PayOrderService;

  @Inject()
  pluginService: PluginService;

  @Inject()
  userWxService: UserWxService;

  // PayOrderEntity
  @InjectEntityModel(PayOrderEntity)
  payOrderEntity: Repository<PayOrderEntity>;

  @Inject()
  payBalanceService: PayBalanceService;

  @InjectEntityModel(UserInfoEntity)
  userInfoEntity: Repository<UserInfoEntity>;

  /**
   * 创建充值余额订单
   */
  @Post('/recharge')
  async createRechargeOrder(@Body() body: { amount: number; title?: string }) {
    const { amount, title } = body;
    const userId = this.ctx.user.id;

    if (!amount || amount <= 0) {
      return this.fail('充值金额必须大于0');
    }

    const order = await this.payOrderService.createRechargeOrder(
      userId,
      amount,
      title
    );
    return this.ok(order);
  }

  /**
   * 创建购买流量订单
   */
  @Post('/traffic')
  async createTrafficOrder(
    @Body() body: { amount: number }
  ) {
    const { amount } = body;
    const userId = this.ctx.user.id;

    if (!amount || amount <= 0) {
      return this.fail('订单金额必须大于0');
    }

    // if (!trafficSize || trafficSize <= 0) {
    //   return this.fail('流量包大小必须大于0');
    // }

    const order = await this.payOrderService.createTrafficOrder(
      userId,
      amount,
      // trafficSize,
      // validDays
    );
    return this.ok(order);
  }

  /**
   * 创建电话通知充值订单
   */
  @Post('/call')
  async createCallOrder(@Body() body: { amount: number}) {
    const { amount } = body;
    const userId = this.ctx.user.id;

    if (!amount || amount <= 0) {
      return this.fail('订单金额必须大于0');
    }

    // if (!callMinutes || callMinutes <= 0) {
    //   return this.fail('充值分钟数必须大于0');
    // }

    const order = await this.payOrderService.createCallOrder(
      userId,
      amount,
      // callMinutes
    );
    return this.ok(order);
  }

  /**
   * 创建物联网卡充值订单
   */
  @Post('/iot')
  async createIotCardOrder(
    @Body() body: { amount: number; iccid: string; trafficSize: number }
  ) {
    const { amount, iccid, trafficSize } = body;
    const userId = this.ctx.user.id;

    if (!amount || amount <= 0) {
      return this.fail('订单金额必须大于0');
    }

    if (!iccid) {
      return this.fail('物联网卡ICCID不能为空');
    }

    if (!trafficSize || trafficSize <= 0) {
      return this.fail('充值流量必须大于0');
    }

    const order = await this.payOrderService.createIotCardOrder(
      userId,
      amount,
      iccid,
      trafficSize
    );
    return this.ok(order);
  }

  /**
   * 创建短信通知充值订单
   */
  @Post('/sms')
  async createSmsOrder(@Body() body: { amount: number; }) {
    const { amount } = body;
    const userId = this.ctx.user.id;

    if (!amount || amount <= 0) {
      return this.fail('订单金额必须大于0');
    }

    // if (!smsCount || smsCount <= 0) {
    //   return this.fail('短信条数必须大于0');
    // }

    const order = await this.payOrderService.createSmsOrder(
      userId,
      amount,
      // smsCount
    );
    return this.ok(order);
  }

  /**
   * 支付订单
   */
  @Post('/pay')
  async payOrder(
    @Body() body: { orderId: number; paymentMethod: number; paymentInfo?: any }
  ) {
    const { orderId, paymentMethod, paymentInfo } = body;

    if (!orderId) {
      return this.fail('订单ID不能为空');
    }

    if (paymentMethod === undefined) {
      return this.fail('支付方式不能为空');
    }

    const result = await this.payOrderService.payOrder(
      orderId,
      paymentMethod,
      paymentInfo
    );
    return this.ok(result);
  }

  /**
   * 取消订单
   */
  @Post('/cancel')
  async cancelOrder(@Body() body: { orderId: number }) {
    const { orderId } = body;

    if (!orderId) {
      return this.fail('订单ID不能为空');
    }

    const order = await this.payOrderService.cancelOrder(orderId);
    return this.ok(order);
  }

  /**
   * 获取用户订单列表
   */
  @Get('/list')
  async getUserOrders(@Query() query: { page?: number; size?: number }) {
    const { page = 1, size = 10 } = query;
    const userId = this.ctx.user.id;

    const result = await this.payOrderService.getUserOrders(userId, page, size);
    return this.ok(result);
  }

  /**
   * 获取订单详情
   */
  @Get('/info')
  async getOrderInfo(@Query() query: { id: number }) {
    const { id } = query;
    const userId = this.ctx.user.id;

    if (!id) {
      return this.fail('订单ID不能为空');
    }

    const order = await this.payOrderService.payOrderEntity.findOne({
      where: { id, userId },
    });

    if (!order) {
      return this.fail('订单不存在');
    }

    return this.ok(order);
  }

  // 测试支付
  @Post('/testPay')
  async testPay(@Body() body: { id: number }) {
    // 获得微信支付 SDK 实例
    const instance = await this.pluginService.invoke('pay-wx', 'getInstance');

    const _res = await instance.transactions_jsapi({
      description: '测试',
      out_trade_no: 'qwerqwerqwer',
      notify_url: 'https://haiqilink.com/api',
      amount: {
        total: 1,
      },
      payer: {
        openid: 'oO6AG7pVFjdUdDK45SEYBQgY6YvY',
      },
      scene_info: {
        payer_client_ip: 'ip',
      },
    });

    console.log('_res_res_res', _res);
  }

  // 支付回调
  // 不需要登陆
  @CoolTag(TagTypes.IGNORE_TOKEN)
  // 注意开放这个接口，不要做token验证
  @Post('/wxNotify', { summary: '微信支付回调' })
  async wxNotify(@Body() body) {
    console.log('获取回调', body);
    //   body = {
    //   id: '2ce35c2f-1878-5c9f-a40c-311c9dfb0113',
    //   create_time: '2025-10-07T00:43:18+08:00',
    //   resource_type: 'encrypt-resource',
    //   event_type: 'TRANSACTION.SUCCESS',
    //   summary: '支付成功',
    //   resource: {
    //     original_type: 'transaction',
    //     algorithm: 'AEAD_AES_256_GCM',
    //     ciphertext: '3IxUZ9+9u2h6LnlS1o/R0Bo297QOFLLmTtBa4U7D/JH8RWFmH/L+CWpUjrtCURhAvpbkQoV7BFXBtA8hYS9sGwjy3QCMCpCixg0M9Yh4moZoO5km7J9wwhfwQDhwRgsROSzk43yJQ4b5PsbTcdp9tbcV/RZlOI/r+Caes6QDLp1eOzYVy1ZRoxGrnHpmGkEffkkPJuZ7UrxV5bz9KHX1pR4GAZ3KYzO4Dma72JmWJrwH3ifC3v5RbZTl+CdAgPToCla56XTOjFJdVreE0ZpLlgQj+7Ewli1ABfdn/BU3Qrcc0t3GPjn/oF1c9yIptQV/KOODqJUhzHBVUGMQhKiE1HTSvEA1KJIGiiZTe/4w7zXbsaLIW7cL0rey7murFnOcy12nw+aIWl2yb0uPBuxy/+zemyXia/WZLVRfRrsLX9ZfUckfI+ePJEvagla+Jh847slynXNWKd2WDAfJW5g+lKDLsp9WhVvOIKWG6sWWqO4/aaoEIqsMK04bLedm1uTsP2NvnQgDW/lLjuQBTlOccWl5OQ2nO3CNZkZj++shdSfbVmCbH6MXwT4Ip3FAWN3WMcKT1Q==',
    //     associated_data: 'transaction',
    //     nonce: 'gzXUNwG0CPs6'
    //   }
    // }

    // 获得插件实例
    const plugin = await this.pluginService.getInstance('pay-wx');

    // 获得微信支付 SDK 实例
    const instance = await plugin.getInstance();

    const { ciphertext, associated_data, nonce } = body.resource;
    const data: any = instance.decipher_gcm(ciphertext, associated_data, nonce);
    const check = await plugin.signVerify(this.ctx);
    console.log('收到支付回调', data);

    // 验签通过，处理业务逻辑
    if (check && data.trade_state == 'SUCCESS') {
      // 处理业务逻辑
      console.log('支付成功', data);

      // 修改订单的状态
      const _order = await this.payOrderEntity.update(
        { orderNo: data.out_trade_no },
        {
          status: 1,
        }
      );

      // 查看订单
      const _orderInfo = await this.payOrderEntity.findOneBy({
        orderNo: data.out_trade_no,
      });

      // 如果是余额充值
      if (_orderInfo.orderType === 0) {
        await this.payBalanceService.addBalance(
          _orderInfo.userId,
          _orderInfo.rechargeAmount,
          _orderInfo.id,
          _orderInfo.orderNo,
          '余额充值',
          0
        );
      }
      // 如果是流量充值
      else if (_orderInfo.orderType === 4) {

        // 先查当前用户的流量
        const _userInfo = await this.userInfoEntity.findOneBy({
          id: _orderInfo.userId,
        });

        // 通过订单userid去充值流量
        await this.userInfoEntity.update(
          { id: _orderInfo.userId },
          {
            smsCount: _userInfo.smsCount + _orderInfo.rechargeAmount,
          }
        );

      }
      // 如果是电话通知
      else if (_orderInfo.orderType === 2) {

        // 先查当前用户的流量
        const _userInfo = await this.userInfoEntity.findOneBy({
          id: _orderInfo.userId,
        });

        // 通过订单userid去充值流量
        await this.userInfoEntity.update(
          { id: _orderInfo.userId },
          {
            smsCount: _userInfo.callMinutes + _orderInfo.rechargeAmount,
          }
        );

      }

      console.log('修改后的dingdan', _order);
    }
    return 'success';
  }
}
